/*
* @Author: dengjiayao
* @Date:   2017-08-28 17:19:29
* @Last Modified by:   dengjiayao
* @Last Modified time: 2017-12-20 16:31:39
*/
import { modal } from 'vue-strap'
import {
  showMsg,
  getSubscribeCourseList,
  getSubscribeCourseDuration,
  subscribeCourse
} from '../../vuex/action'

export default {
  data() {
    return {
      showModal: false,
      actionType: 'ADD', // ADD or UPDATE
      form: {
        phone: '',
        courseId: '',
        dateNum: ''
      },
      courseList: [],
      courseDuration: []
    }
  },
  components: {
    'vue-modal': modal
  },
  vuex: {
    actions: {
      xShowMsg: showMsg,
      xGetList: getSubscribeCourseList,
      xGetDuration: getSubscribeCourseDuration,
      xSubscribe: subscribeCourse
    }
  },
  created() {
    this.xGetList({ start: 0, limit: 1000 }).then(ret => {
      for (let k in ret) {
        this.courseList.push({ key: k, value: ret[k] })
      }
    })
  },
  methods: {
    valid() {
      let fields = ['phone', 'courseId', 'dateNum']
      for (let k of fields) {
        let v = this.form[k] + ''
        if (v.length === 0) {
          return Promise.reject({
            error_msg: '*标识的均为必填项'
          })
        }
      }
      return Promise.resolve()
    },
    submit() {
      this.valid()
        .then(() => {
          let form = this.form
          return this.xSubscribe(form)
        })
        .then(() => {
          this.showModal = false
        })
        .catch(res => {
          this.xShowMsg({
            type: 'danger',
            content: res.error_msg
          })
        })
    }
  },
  watch: {
    'form.courseId': function(val) {
      this.form.dateNum = ''
      if (val) {
        this.xGetDuration({
          courseId: val
        }).then(durationList => {
          this.courseDuration = durationList.map(it => {
            return {
              key: it.duration,
              value: it.duration + '日'
            }
          })
        })
      } else {
        this.courseDuration = []
      }
    }
  }
}
